import 'dart:io';
import 'dart:typed_data';
import 'package:animation/generated/l10n.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:gallery_saver_plus/gallery_saver.dart';
import 'package:image_gallery_saver_plus/image_gallery_saver_plus.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:dio/dio.dart';

class DownImage {
  /// 获取应用总缓存大小 (单位: MB)
  static Future<double> getTotalCacheSize() async {
    double totalSize = 0;
    final tempDir = await getTemporaryDirectory();
    totalSize += await _getFolderSize(tempDir);
    return totalSize;
  }

  /// 清理所有缓存
  static Future<void> clearAllCache() async {
    // 1. 清理内存中的图片缓存
    imageCache.clear();
    imageCache.clearLiveImages();

    // 2. 清理磁盘中的图片缓存
    await DefaultCacheManager().emptyCache();
    await clearExtendedImageCache();

    // 3. 清理临时目录
    final tempDir = await getTemporaryDirectory();
    await _deleteFolder(tempDir);

    // 4. 清理其他缓存（按需添加）
    // await SharedPreferences.getInstance().then((prefs) => prefs.clear());
    // await Hive.deleteFromDisk();
  }

  /// 清理 extended_image 特殊缓存
  static Future<void> clearExtendedImageCache() async {
    try {
      final directory = Directory(
          '${(await getTemporaryDirectory()).path}/extended_image_cache');
      if (directory.existsSync()) {
        await directory.delete(recursive: true);
      }
    } catch (e) {
      debugPrint('清理extended_image缓存失败: $e');
    }
  }

  /// 计算文件夹大小
  static Future<double> _getFolderSize(Directory dir) async {
    if (!dir.existsSync()) return 0;

    int totalBytes = 0;
    final files = dir.listSync(recursive: true);

    await Future.forEach(files, (file) async {
      if (file is File) {
        totalBytes += await file.length();
      }
    });

    return totalBytes / (1024 * 1024);
  }

  /// 删除文件夹
  static Future<void> _deleteFolder(Directory dir) async {
    if (dir.existsSync()) {
      // ignore: body_might_complete_normally_catch_error
      await dir.delete(recursive: true).catchError((e) {
        debugPrint('删除文件夹失败');
      });
    }
  }

  /// 下载网络图片（先读缓存资源，缓存没有再重新获取资源）
  static Future<String> downloadNetworkImage(
      String imagePath, BuildContext context) async {
    var status = await Permission.storage.status;
    if (!status.isGranted) {
      //未授予
      Permission.storage.request();
    }
    const String prefix = 'App-Save';
    // 获取缓存图片
    var cacheData = await getNetworkImageData(imagePath, useCache: true);
    // 获取当前时间戳
    int timestamp = DateTime.now().millisecondsSinceEpoch;
    // 将时间戳转换为可读的日期格式
    String dateTime = DateTime.fromMillisecondsSinceEpoch(timestamp).toString();
    // 拼接名字
    String saveName = '$prefix-$dateTime';

    var loadingBot = BotToast.showCustomLoading(
        backgroundColor: const Color.fromARGB(100, 4, 4, 4),
        toastBuilder: (cancel) {
          return Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              CircularProgressIndicator(),
              SizedBox(height: 10),
              Text(
                S.of(context).s14,
                style: TextStyle(color: Colors.white, fontSize: 13),
              ),
            ],
          );
        });

    // 下载逻辑
    late dynamic result;
    // 如果缓存图片不为空
    if (cacheData != null) {
      result = await ImageGallerySaverPlus.saveImage(
        cacheData,
        quality: 100,
        name: saveName,
      );
    } else {
      var response = await Dio()
          .get(imagePath, options: Options(responseType: ResponseType.bytes));
      result = await ImageGallerySaverPlus.saveImage(
        Uint8List.fromList(response.data),
        quality: 100,
      );
    }
    if (result["isSuccess"]) {
      loadingBot();
      BotToast.showText(text: S.of(context).s1);
      return result["filePath"];
    } else {
      loadingBot();
      return 'error';
    }
  }

  Future<String?> setWallpaper(String url) async {
    try {
      final dir = await getTemporaryDirectory();
      final filename = url.split('/').last;
      final path = '${dir.path}/$filename';
      // 先读取缓存中的图片 存在缓存则直接返回
      final cacheData = await getNetworkImageData(url, useCache: true);
      if (cacheData != null) {
        await File(path).writeAsBytes(cacheData);
        return path;
      } else {
        final response = await Dio().download(url, path);
        if (response.statusCode == 200) {
          return path;
        }
        return null;
      }
    } catch (e) {
      print('下载失败');
      return null;
    }
  }

  // 下载视频到相册
  Future<String?> downVideo(String url, BuildContext context) async {
    try {
      // 请求存储权限
      var status = await Permission.storage.status;
      if (!status.isGranted) {
        // 未授予
        await Permission.storage.request();
      }

      // 获取相册目录
      final directory = await getExternalStorageDirectory();
      final filename = Uri.parse(url).pathSegments.last;
      final filePath = '${directory?.path}/Download/$filename';

      // 确保目录存在
      final downloadDir = Directory('${directory?.path}/Download');
      if (!downloadDir.existsSync()) {
        downloadDir.createSync();
      }

      // 检查文件是否已经存在
      if (File(filePath).existsSync()) {
        return filePath;
      }

      var loadingBot = BotToast.showCustomLoading(
          backgroundColor: const Color.fromARGB(100, 4, 4, 4),
          toastBuilder: (cancel) {
            return Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CircularProgressIndicator(),
                SizedBox(height: 10),
                Text(
                  S.of(context).s3,
                  style: TextStyle(color: Colors.white, fontSize: 13),
                ),
              ],
            );
          });

      // 使用 Dio 下载文件
      final dio = Dio();
      await dio.download(
        url,
        filePath,
        onReceiveProgress: (received, total) {
          if (total != -1) {}
        },
      );

      // 刷新媒体库（可选）
      // 如果需要让相册应用识别新文件，可以调用媒体扫描
      await GallerySaver.saveVideo(filePath);
      loadingBot();
      return filePath;
    } catch (e) {
      return null;
    }
  }
}
